use JSON;

$HOME_DIR = "/home/limura";
$WGET = "/usr/bin/wget";
$|=1;
print("Content-Type: application/octet-stream\r\n\r\n");

unless(chdir($HOME_DIR)){
	&PrintError("can not chdir to $HOME_DIR.");
	exit(0);
}
#unless(-f 'config.ph'){
#	&PrintError("config file not found.");
#	exit(0);
#}
$ENV{'CHOPSET_HOME'} = $HOME_DIR;
#require "$HOME_DIR/config.ph";

sub PrintError{
	my($msg) = @_;
	my($jsonObj) = {
		Result => "error",
		Description => $msg
	};
	print to_json($jsonObj);
}

sub PrintResult{
	my($msg, $resultObj) = @_;
	my($jsonObj) = {
		Result => "success",
		Description => $msg,
		Argument => $resultObj
	};
	print to_json($jsonObj);
}

sub ClearPoint{
	my(@users) = &GetUserNames();
	if(open(FILE, "+<$HOME_DIR/Game/Points.txt")){
		flock(FILE, 2);
		seek(FILE, 0, 0);
		my($buf) = join('', <FILE>);
		$buf =~ s/:\d+/:0/g;
		truncate(FILE, length($buf));
		seek(FILE, 0, 0);
		print FILE $buf;
		close(FILE);
	}
}

sub GetPoint{
	my($userName) = @_;
	if(open(FILE, "<$HOME_DIR/Game/Points.txt")){
		flock(FILE, 1);
		seek(FILE, 0, 0);
		my($buf) = join('', <FILE>);
		flock(FILE, 8);
		close(FILE);
		if($buf =~ m/"$userName":(\d+)/){
			return $1 + 0;
		}
	}
	return -1;
}

sub AddPoint{
	my($userName, $point) = @_;
	if(open(FILE, "+<$HOME_DIR/Game/Points.txt")){
		flock(FILE, 2);
		seek(FILE, 0, 0);
		my($buf) = join('', <FILE>);
		seek(FILE, 0, 0);
		$buf =~ s/"$userName":(\d+)/sprintf('"%s":%d', $userName, $1 + $point)/e;
		truncate(FILE, length($buf));
		print FILE $buf;
		flock(FILE, 8);
		close(FILE);
	}
}

sub GetMasterURL{
	my($userName) = @_;
	if(open(FILE, "<$HOME_DIR/Game/UserSetting.txt")){
		while(<FILE>){
			if(m/^$userName\s+([^\s]+)/){
				close(FILE);
				return $1;
			}
		}
		close(FILE);
	}
	return undef;
}

sub GetUserNames{
	my(@users);
	if(open(FILE, "<$HOME_DIR/Game/UserSetting.txt")){
		while(<FILE>){
			if(m/^([^\s]+)/){
				push(@users, $1);
			}
		}
		close(FILE);
	}
	return @users;
}

sub GetJobNames{
	my(@jobs);
	if(opendir(DIR, "$HOME_DIR/Game/jobs")){
		while($file = readdir(DIR)){
			next if(m/^\./);
			next unless(-r "$HOME_DIR/Game/$file");
			push(@jobs, $file);
		}
		closedir(DIR);
	}
	return @jobs;
}

1;
